package com.fenghuajueli.libbasecoreui.widget

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.util.AttributeSet
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebChromeClient.FileChooserParams
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.fenghuajueli.libbasecoreui.ui.CustomerServiceActivity

class ProgressWebview : WebView {
    //进度条
    private lateinit var progressView: ProgressView
    private var context: Context
    private var data = ""

    private var isArticle: Boolean = false

    // 是否配置黑天模式
    private var mLightModeStatus = false

    private var webViewListener: WebViewListener? = null

    constructor(context: Context, isArticle: Boolean) : this(context) {
        this.isArticle = isArticle
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(context, attrs, defStyleAttr, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        this.context = context
        init()
    }

    fun setWebViewListener(webViewListener: WebViewListener) {
        this.webViewListener = webViewListener
    }

    private fun init() {
        //初始化进度条
        progressView = ProgressView(context).apply {
            layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(context, 4f))
            setColor(Color.BLUE)
            setProgress(10)
        }
        //把进度条加到Webview中
        addView(progressView)
        //初始化设置
        initWebSettings()
        webChromeClient = MyWebCromeClient()
        webViewClient = MyWebviewClient()
    }

    private fun initWebSettings() {
        val settings = settings
        //默认是false 设置true允许和js交互
        settings.javaScriptEnabled = true
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        //开启 DOM storage API 功能 较大存储空间，使用简单
        settings.domStorageEnabled = true
        //解决图片不显示
        settings.blockNetworkImage = false
        settings.databaseEnabled = true
        val dbPath = context.applicationContext.getDir("db", Context.MODE_PRIVATE).path
        settings.databasePath = dbPath
    }

    //weui-flex__item
    private inner class MyWebCromeClient : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                //加载完毕进度条消失
                progressView.visibility = GONE
            } else {
                //更新进度
                progressView.setProgress(newProgress)
            }
            //移除网页中的阅读原文元素
            view.loadUrl("javascript:function setTop(){document.querySelector('.weui-flex__item').style.display=\"none\";}setTop();")
            super.onProgressChanged(view, newProgress)
        }

        override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
            webViewListener?.openFile(filePathCallback, fileChooserParams)
            return true
        }
    }

    /**
     * 设置隐私政策里的权限说明数据
     *
     * @param data
     */
    fun setData(data: String) {
        this.data = data
    }

    /**
     * 设置黑白天主题样式
     */
    fun setStatusLightMode(status: Boolean) {
        this.mLightModeStatus = status
    }

    private inner class MyWebviewClient : WebViewClient() {
        @Deprecated("Deprecated in Java")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            if (isArticle) {
                openBrowser(context,url)
                return true
            }
            if (url.startsWith("https://www.bestkids.net/chatlink.html?eid")) {
                CustomerServiceActivity.start(getContext())
                return true
            }
            if (url.startsWith("tel:")) {
                val mobile = url.substring(url.lastIndexOf(":") + 1)
                ClipboardUtils.copyText(mobile)
                ToastUtils.showShort("复制成功")
                openBrowser(getContext(), url)
                return true
            }
            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            val url = request.url
            if (url.toString().startsWith("https://www.bestkids.net/chatlink.html?eid")) {
                CustomerServiceActivity.start(getContext())
                return true
            }
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageFinished(view: WebView, url: String) {
            view.loadUrl("javascript:function setTop(){document.querySelector('.weui-flex__item').style.display=\"none\";}setTop();")
            if (isArticle) {
                //移除网页文章底部元素
                view.loadJs()
            }
            if (!TextUtils.isEmpty(data)) {
                val js = "window.localStorage.setItem('privacyKey','$data');"
                val jsUrl = "javascript:(function({ var localStorage = window.localStorage; localStorage.setItem('privacyKey','$data') })()"
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    view.evaluateJavascript(js, null)
                } else {
                    view.loadUrl(jsUrl)
                    view.reload()
                }
                //通过js注入修改网页背景颜色和文字颜色
                if (mLightModeStatus) {
                    //黑天
                    loadUrl(
                        "javascript:function getSub(){" +
                                "document.getElementsByTagName('body')[0].style.color='#FFFFFF'" +
                                "};getSub();"
                    )
                    loadUrl(
                        "javascript:function getSub(){" +
                                "document.getElementsByTagName('body')[0].style.background='#000000'" +
                                "};getSub();"
                    )
                } else {
                    //白天
                    loadUrl(
                        "javascript:function getSub(){" +
                                "document.getElementsByTagName('body')[0].style.color='#000000'" +
                                "};getSub();"
                    )
                    loadUrl(
                        "javascript:function getSub(){" +
                                "document.getElementsByTagName('body')[0].style.background='#FFFFFF'" +
                                "};getSub();"
                    )
                }
            }
            super.onPageFinished(view, url)
        }

        override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)
        }
    }

    fun openBrowser(context: Context, url: String?) {
        runCatching {
            val intent = Intent()
            intent.setAction(Intent.ACTION_VIEW)
            intent.setData(Uri.parse(url))
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"))
        }
    }

    /**
     * dp转换成px
     *
     * @param context Context
     * @param dp      dp
     * @return px值
     */
    private fun dp2px(context: Context, dp: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dp * scale + 0.5f).toInt()
    }

    interface WebViewListener {
        /**
         * 触发了打开文件选择的操作
         *
         * @param filePathCallback
         * @param fileChooserParams
         */
        fun openFile(filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?)
    }

    private fun WebView.loadJs() {
        evaluateJavascript(
            """
            (function() {
                document.getElementById('js_content_end').remove();
                document.getElementById('js_article_bottom_bar').style.display = 'none';
                const targetNode = document.body;
                const observer = new MutationObserver(function(mutationsList, observer) {
                    for(let mutation of mutationsList) {
                        if (mutation.type === 'childList') {
                            console.log('A child node has been added or removed.');
                            document.getElementsByClassName('jump-weixin-dialog')[0].remove();
                        }
                        else if (mutation.type === 'attributes') {
                            console.log('The ' + mutation.attributeName + ' attribute was modified.');
                        }
                    }
                });
                const config = { attributes: false, childList: true, subtree: false };
                observer.observe(targetNode, config);
            })();
        """.trimIndent(), null
        )
    }
}
